import { ENUM_ERROR, ExtOwner } from "qqlx-core";

type SetValue<T> = {
  /** 去重后的数组中，首个元素 */
  first?: T;

  /** 去重后的数组 */
  values: T[];

  /** 去重后有多少元素 */
  count: number;
};

/** 数组去重并返回唯一重复的值 */
export function getSetData<T extends number | string>(list: T[]): SetValue<T> {
  const values = Array.from(new Set(list));
  return {
    first: values[0],
    values,
    count: values.length,
  };
}

/** 返回唯一的管理人 */
export function getSetMaster(list: ExtOwner[]) {
  const { count, first } = getSetData(list.map((d) => d.refOwnerUUid32));
  if (count !== 1) throw { code: ENUM_ERROR.ACCOUNT_DISLOCATION };
  return { masterId: first as ExtOwner["refOwnerUUid32"] };
}

/** 英文标点符号 */
const PointsEn = [
  "!",
  '"',
  "#",
  "$",
  "%",
  "&",
  "'",
  "(",
  ")",
  "*",
  "+",
  ",",
  "-",
  ".",
  "/",
  ":",
  ";",
  "<",
  "=",
  ">",
  "?",
  "@",
  "[",
  "\\",
  "]",
  "^",
  "_",
  "`",
  "{",
  "|",
  "}",
  "~",
];

/** 中文标点符号 */
const PointsZh = ["，", "。", "！", "？", "；", "：", "“", "”", "‘", "’"];

/** 中文|英文|中文标点符号|英文标点符号|数字 */
export const RegularZhMap = [
  // 中文字符范围
  ...Array.from({ length: 100 }, (_, i) => String.fromCharCode(0x4e00 + i)), // 常用汉字
  // 英文字符
  ...Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i)), // 大写字母 A-Z
  ...Array.from({ length: 26 }, (_, i) => String.fromCharCode(97 + i)), // 小写字母 a-z
  // 中文标点符号
  ...PointsZh,
  // 英文标点符号
  ...PointsEn,
  // 数字
  ...Array.from({ length: 10 }, (_, i) => String.fromCharCode(48 + i)), // 数字 0-9
];

/** 随机生成指定个数（RegularZhMap）*/
export function getRegularZhStr(len = 6) {
  return Array.from({ length: len }, () => RegularZhMap[Math.floor(Math.random() * RegularZhMap.length)]).join("");
}

/** 随机生成指定个数（RegularZhMap）的字符串数组
 * @ls 数组长度
 * @str 每个字符串长度
 */
export function getRegularZhStrList(ls = 6, str = 6) {
  return Array.from({ length: ls }, () => getRegularZhStr(str));
}

/** 保证一个字符串中，只包含 RegularZhMap 数组中的字符 */
export function filterRegularZhStr(str: string) {
  const ls = str.split("");
  return ls.filter((item) => RegularZhMap.includes(item)).join("");
}

/** 对字符串数组进行排序
 * @step1 仅仅保留字符串中的中文、英文、中文标点符号、英文标点符号、数字
 * @step2 对字符串进行排序
 */
export function doRegularZhSort(list: string[]) {
  return list.filter((d) => !!d).sort((a, b) => a.localeCompare(b, "zh-Hans"));
}

/** 比较两个字符串数组，它们的长度、内容最终是否一致 */
export function compareStrList(list1: string[], list2: string[]) {
  const charge1 = list1.length === list2.length;
  const charge2 = list1.every((item) => list2.includes(item));
  return charge1 && charge2;
}
